// components/confirm/uploadFile/uploadFile.js
import { upload } from '../../../js/modules/material.js'
import { alert } from '../../../js/newUtil.js'
import { util, api } from '../../../js/util'
import authorize from '../../../js/modules/authorize.js'
const componentBehavior = require('../../../js/common/ComponentBehavior')

Component({
  behaviors: [componentBehavior],
  /**
   * 组件的属性列表
   */
  properties: {
    componentStyle: {
      type: String,
      value: 'v2'
    },
    max: {
      type: Number,
      value: 9
    },
    type: { // 上传的文件类型, all: 图片或文件 image: 图片
      type: String,
      value: 'all'
    },
    hideUpload: { // 是否隐藏上传按钮
      type: Boolean,
      value: false
    },
    hideDelete: { // 是否隐藏删除按钮
      type: Boolean,
      value: false
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    fileList: [],
    imgDomain: api.imgDomain,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 删除文件
     * @param {*} e 
     */
    deleteFile(e) {
      let index = e.currentTarget.dataset.index
      let fileList = this.data.fileList
      fileList.splice(index, 1)
      this.setData({
        fileList
      }, () => {
        this.onChange()
      })
    },
    /**
     * 选择上传的文件类型
     */
    chooseUploadFile() {
      // 登录后才能上传
      if (!authorize.isLogin('store')) {
        authorize.redirect('store')
        return
      }
      let that = this
      let fileList = this.data.fileList || []
      let max = this.data.max || 9
      let type = this.data.type
      let count = max - fileList.length
      if (count <= 0) {
        return
      }
      if (type == 'image') {
        that.chooseImage(count)
        return
      }
      if (type == 'file') {
        that.chooseFile(count)
        return
      }
      wx.showActionSheet({
        itemList: ['选择图片', '选择文件'],
        success (res) {
          if (res.tapIndex == 0) {
            that.chooseImage(count)
          } else {
            that.chooseFile(count)
          }
        }
      })
    },
    /**
     * 上传文件
     * @param {*} count 可上传的数量
     */
    chooseFile(count) {
      let that = this
      let fileList = this.data.fileList || []
      const MAX_FILE_SIZE = 20 * 1024 * 1024 // 最大20MB的文件
      const allowedFileTypeList = ['jpeg', 'png', 'jpg', 'ico', 'gif', 'bmp', 'doc', 'docx', 'folder', 'mp3', 'mp4', 'pdf', 'rar', 'txt', 'xls', 'xlsx', 'zip']
      wx.chooseMessageFile({
        count,
        success (res) {
          let tempFiles = res.tempFiles || []
          let outSize = []
          let files = []
          for (let i in tempFiles) {
            if (tempFiles[i].size > MAX_FILE_SIZE) {
              outSize.push(tempFiles[i].name)
            }
            if (tempFiles[i].type != 'image') {
              let type = getExtention(tempFiles[i].name) || tempFiles[i].type
              type = type.toLocaleLowerCase()
              if (!allowedFileTypeList.includes(type)) {
                wx.showModal({
                  title: '上传文件失败',
                  content: `不支持${type}文件上传，仅支持以下文件类型${allowedFileTypeList.join(',')}`,
                  showCancel: false
                })
                return
              }
              tempFiles[i].type = type
              tempFiles[i].fileIcon = getFileIcon(tempFiles[i].type)
            }
            files.push(tempFiles[i].path)
          }
          if (outSize.length > 0) {
            outSize = outSize.join(',')
            alert({
              content: `以下文件超过最大可上传大小（20MB）：${outSize}`
            })
            return
          }
          let data = {
            num: 3001,
            type:3,
            tempFilePaths: files
          }
          upload.upload_image_server(data, function (files) {
            if (files.length==0){
              util.alert("上传文件失败")
              return
            }
            for (let i = 0; i < tempFiles.length; i++) {
              files[i] = {
                src: files[i],
                type: tempFiles[i].type,
                name: tempFiles[i].name,
                fileIcon: tempFiles[i].fileIcon
              }
            }
            fileList = [...fileList, ...files]
            that.setData({
              fileList
            }, function () {
              that.onChange()
            })
          })
        },
        fail (err) {
          console.log('选择文件失败', err)
        }
      })
    },
    /**
     * 上传图片
     * @param {*} count 可上传的数量
     */
    chooseImage(count) {
      let that = this
      let fileList = this.data.fileList
      wx.chooseImage({
        count,
        success (res) {
          let data = {
            num: 1010,
            type:1,
            tempFilePaths: res.tempFilePaths
          }
          upload.upload_image_server(data, function (imgList) {
            if (imgList.length==0){
              util.alert("上传图片失败")
              return
            }
            imgList = imgList.map((item) => {
              let name = getName(item)
              return {
                src: item,
                type: 'image',
                name: name
              }
            })
            fileList = [...fileList, ...imgList]
            that.setData({
              fileList
            }, function () {
              that.onChange()
            })
          })
        },
        fail (err) {
          console.log('选择图片失败', err)
        }
      })
    },
    /**
     * 变更事件
     */
    onChange() {
      let fileList = this.data.fileList
      this.triggerEvent('onChange', {
        fileList
      })
    },
    tapItem (e) {
      let fileList = this.data.fileList
      let imgDomain = this.data.imgDomain
      let index = e.currentTarget.dataset.index
      let type = fileList[index].type
      if (type == 'image') { // 如果是图片,点击后预览全部的图片
        let imgList = []
        let current = ''
        for (let i = 0; i < fileList.length; i++) {
          if (fileList[i].type == 'image') {
            imgList.push(imgDomain + fileList[i].src)
            if (index == i) {
              current = imgDomain + fileList[i].src
            }
          }
        }
        wx.previewImage({
          urls: imgList,
          current
        })
      } else {
        wx.setClipboardData({
          data: imgDomain + fileList[index].src,
          success () {
            alert('复制链接成功，请在浏览器中进行下载')
          }
        })
      }
    },
    setList (fileList = []) {
      fileList = fileList.map(item => {
        let img = ['jpg', 'jpeg', 'webp', 'png', 'bmp', 'gif', 'ico', 'pic']
        item.src = item.src || item.Url
        item.name = item.name || item.FileName
        if (!item.name) {
          item.name = getName(item.src)
        }
        let type = item.type || item.TYPE
        let fileIcon = getFileIcon(type)
        if (img.includes(type)) {
          type = 'image'
        } else {
          item.fileIcon = fileIcon
        }
        item.type = type
        return item
      })
      console.log(fileList)
      this.setData({
        fileList
      })
    }
  }
})

/**
 * 获取文件拓展名
 */
let getExtention = (name = '') => {
  let arr = name.split('.')
  if (arr.length == 0) {
    return ''
  }
  return arr[arr.length - 1]
}

/**
 * 获取文件名
 * @param {*} name 
 */
let getName = (name) => {
  let result = ''
  try {
    let arr = name.split('/')
    result = arr[arr.length - 1]
    return result
  } catch (error) {
    return name
  } 
}

/**
 * 获取文件对应显示的图标
 * @param {*} ext 拓展名
 */
let getFileIcon = (ext = '') => {
  ext = ext.toLocaleLowerCase()
  return '/assets/images/fileIcon/' + ext + '.png'
}
